package com.netty.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyServerHandler extends SimpleChannelInboundHandler<String> {
    /**
     * @param ctx 可以拿到本次处理的上下文信息
     * @param msg 就是获取到的信息
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("客户端信息：{}" + ctx.channel().remoteAddress());

        JSONObject jsonObject = JSON.parseObject(msg);
        log.info("来自客户端的问候信息:{}", jsonObject);

        String name = jsonObject.getString("name");

        ctx.writeAndFlush("来自服务端的问候：你好," + name);
    }

    /**
     * @param ctx   当前的应用上下文
     * @param cause Throwable是异常和Error的顶级接口,此处就是异常
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //有异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }


}
